package com.mq.dpca.msg;

import java.util.Hashtable;


import com.ibm.mq.MQException;
import com.ibm.mq.MQGetMessageOptions;
import com.ibm.mq.MQMessage;
import com.ibm.mq.MQQueue;
import com.ibm.mq.MQQueueManager;
import com.ibm.mq.constants.MQConstants;

public class MqGetSampen {
	@SuppressWarnings("rawtypes")
	private static Hashtable<String, Comparable> env = new Hashtable<String, Comparable>();

	private static String queueManagerName;
	private static MQQueueManager queueManager;
	private static String queueName;
	private MQQueue queue;

	/**
	 * 
	 * @throws Exception
	 */
	public static void initEnvironment() throws Exception {
		env.put(MQConstants.HOST_NAME_PROPERTY, "localhost");
		env.put(MQConstants.CHANNEL_PROPERTY, "SYSTEM.DEF.SVRCONN");
		env.put(MQConstants.CCSID_PROPERTY, 1208);
		env.put(MQConstants.PORT_PROPERTY, 1414);
		env.put(MQConstants.TRANSPORT_PROPERTY, MQConstants.TRANSPORT_MQSERIES);
		queueManagerName = "QM1";
		queueName = "Q4";
		connectQM();
	}

	/**
	 * �������ʱ�ͷŶ��й���������Դ
	 * 
	 * @throws Exception
	 */
	public static void destroyEnvironment() throws Exception {
		disconnectQM();
	}


	public String getMsg() throws Exception {
		MqGetSampen.initEnvironment();
		int openOptions = MQConstants.MQOO_INPUT_AS_Q_DEF
				| MQConstants.MQOO_OUTPUT | MQConstants.MQOO_FAIL_IF_QUIESCING;

		MQGetMessageOptions gmo = new MQGetMessageOptions();
		gmo.options = MQConstants.MQGMO_SYNCPOINT | MQConstants.MQGMO_WAIT;

		gmo.waitInterval = 1000; // ����

		queue = queueManager.accessQueue(queueName, openOptions);
		try {
			while (true) {

				MQMessage msg = new MQMessage();
				queue.get(msg, gmo);
				int dataLength = msg.getDataLength();

//				String message = msg.readObject().toString();
//				System.out.println(msg.getStringProperty("type"));
				String message = msg.readStringOfByteLength(dataLength);

				System.out.println("当前消息\n" + message + "\n");
				queueManager.commit(); 
//				return message;
			}
		} catch (MQException e) {
			queueManager.backout();
			if (2033 == e.getReason()) {
				System.out.println("数据已取完");
			} else {
				e.printStackTrace();
			}

		} finally {
			if (queue != null) {
				queue.close();
			}
		}
		return null;
	}
	public void commit() throws Exception {
		queueManager.commit();
	}
	private static void connectQM() throws Exception {
		queueManager = new MQQueueManager(queueManagerName, env);
	}

	private static void disconnectQM() throws Exception {
		if (queueManager != null) {
			queueManager.disconnect();
		}
	}
	public static void main(String[] args) throws Exception{
		MqGetSampen getSampen = new MqGetSampen();
		getSampen.getMsg();
	}
}